import $ from 'jquery';

var appID = 'wx91c87c6a3b52b51f'; // 公众号 appID
var appsecret = "a1a925b441bd57aaf3e60944190d65bf" // 公众号appsecretv

$(document).ready(function() {
    // 第一步 获取code 码
    var redirectUrl = encodeURIComponent('http://127.0.0.1:8080/') // 获取code码之后指定的回调地址
    var SCOPE = "snsapi_userinfo"; // 获取用户类型为： 获取用户基础信息
    var wechartUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appID}&redirect_uri=${redirectUrl}&response_type=code&scope=${SCOPE}&state=STATE#wechat_redirect`;
    if (location.href.includes('code')) {
        var str = location.href.split('&');
        var code = str[0].split('=');
        console.log("获取到code", code[1])
        tokenObj = getAccessToken(code[1]);
    } else {
        window.location = wechartUrl;
    }
})

// 第二步 根据code 获取acess_token & openId
function getAccessToken(code) {
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appID}&secret=${appsecret}&code=${code}&grant_type=authorization_code`,
        success: function(res) {
            console.log('token', res);
            var access_token = res.access_token;
            var refresh_token = res.refresh_token;
            var openid = res.openid;
            getUserInfo(access_token, openid)
        },
        error: function(err) {
            console.log('error', err)
        }

    })
}

// 第三步 根据access_token 获取用户基础信息
function getUserInfo(token, openId) {
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: `https://api.weixin.qq.com/sns/userinfo?access_token=${token}&openid=${openId}&lang=zh_CN`,
        success: function(res) {
            console.log('userInfo', res);
        },
        error: function(err) {
            console.log('error', err)
        }

    })
}